<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from 'axios'

const userStore = useUserStore()
const loading = ref(false)

const formRef = ref(null)
const form = reactive({
  id: userStore.userId || 1,
  name: '',
  phone: '',
  email: '',
  departmentId: '',
  departmentName: '',
  position: '',
  createTime: ''
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true
    // 首先尝试从 store 获取最新的用户信息
    await userStore.getUserInfo()
    
    // 如果 store 中已有完整信息，直接使用
    if (userStore.userInfo && userStore.userInfo.id) {
      const userData = userStore.userInfo
      console.log('从 store 获取的用户信息:', userData)
      
      Object.assign(form, {
        id: userData.id,
        name: userData.name || '',
        phone: userData.phone || '',
        email: userData.email || '',
        departmentId: userData.departmentId,
        departmentName: userData.departmentName || '未分配',
        position: userData.position || '',
        createTime: userData.createTime
      })
    } else {
      // 如果 store 中没有完整信息，直接调用 API
      const response = await axios.get(`/users/${userStore.userId}`)
      const userData = response.data
      console.log('后端返回的用户信息:', userData)
      
      Object.assign(form, {
        id: userData.id,
        name: userData.name || '',
        phone: userData.phone || '',
        email: userData.email || '',
        departmentId: userData.departmentId,
        departmentName: userData.departmentName || '未分配',
        position: userData.position || '',
        createTime: userData.createTime
      })
    }
    loading.value = false
  } catch (error) {
    console.error('获取用户信息失败:', error)
    loading.value = false
    ElMessage.error('获取用户信息失败，请重试')
  }
}

// 更新用户信息
const updateUserInfo = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        await axios.put(`/users/${form.id}`, {
          name: form.name,
          phone: form.phone,
          email: form.email,
          departmentId: form.departmentId,
          position: form.position
        })
        ElMessage.success('个人信息更新成功')
        loading.value = false
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新失败，请重试')
        loading.value = false
      }
    }
  })
}

// 修改密码
const changePasswordVisible = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  email: '',
  emailCode: ''
})

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.oldPassword) {
          callback(new Error('新密码不能与原密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  emailCode: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

const passwordFormRef = ref(null)
const sendingCode = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)

const openChangePasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordForm.email = form.email || ''
  passwordForm.emailCode = ''
  changePasswordVisible.value = true
}

// 发送验证码
const sendEmailCode = async () => {
  if (!passwordForm.email) {
    ElMessage.warning('请先输入邮箱地址')
    return
  }
  
  try {
    sendingCode.value = true
    const userId = userStore.userInfo.id
    await axios.post(`/users/${userId}/send-password-verification`, {
      email: passwordForm.email
    })
    ElMessage.success('验证码发送成功，请查收邮件')
    
    // 开始倒计时
    countdown.value = 60
    countdownTimer.value = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer.value)
      }
    }, 1000)
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data)
    } else {
      ElMessage.error('验证码发送失败，请重试')
    }
  } finally {
    sendingCode.value = false
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})

const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 调用后端API
        const userId = userStore.userInfo.id
        const res = await axios.post(`/users/${userId}/change-password`, {
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
          email: passwordForm.email,
          emailCode: passwordForm.emailCode
        })
        ElMessage.success(res.data || '密码修改成功')
        changePasswordVisible.value = false
        loading.value = false
      } catch (error) {
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data)
        } else {
          ElMessage.error('修改失败，请重试')
        }
        loading.value = false
      }
    }
  })
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return String(dateTime)
    }
    // yyyy/M/d HH:mm:ss
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const hh = String(date.getHours()).padStart(2, '0')
    const mm = String(date.getMinutes()).padStart(2, '0')
    const ss = String(date.getSeconds()).padStart(2, '0')
    return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
  } catch (error) {
    return String(dateTime)
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="container">
    <div class="page-header">
      <div class="page-title">个人信息</div>
    </div>
    
    <el-row>
      <el-col :span="24">
        <el-card shadow="never" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
            </div>
          </template>
          
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="form.name" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="部门" prop="departmentName">
                  <el-input v-model="form.departmentName" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="职位" prop="position">
                  <el-input v-model="form.position" disabled />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="入职日期" prop="createTime">
                  <el-input :value="formatDateTime(form.createTime)" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        
        <el-card shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>账号安全</span>
            </div>
          </template>
          
          <div class="security-item">
            <div class="security-info">
              <div class="security-title">登录密码</div>
              <div class="security-desc">定期修改密码可以保护账号安全</div>
            </div>
            <el-button type="primary" @click="openChangePasswordDialog">修改密码</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="changePasswordVisible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            placeholder="请输入原密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请确认新密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="邮箱地址" prop="email">
          <el-input 
            v-model="passwordForm.email" 
            placeholder="请输入邮箱地址" 
          />
        </el-form-item>
        
        <el-form-item label="验证码" prop="emailCode">
          <div style="display: flex; gap: 10px;">
            <el-input 
              v-model="passwordForm.emailCode" 
              placeholder="请输入6位验证码" 
              style="flex: 1;"
            />
            <el-button 
              type="primary" 
              :disabled="sendingCode || countdown > 0"
              @click="sendEmailCode"
              style="width: 120px;"
            >
              {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="changePasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.security-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.security-desc {
  color: #999;
  font-size: 14px;
}

.container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

/* 添加响应式卡片样式 */
:deep(.el-card) {
  margin-bottom: 20px;
}

:deep(.el-row) {
  width: 100%;
}
</style> 